package net.droiding.activity;

import net.droiding.R;
import net.droiding.app.Droiding;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class RegisterActivity extends Activity {

	private Button btnOk = null;
	private EditText txtUsername = null;
	private EditText txtPassword = null;
	private Droiding droiding = null;
	private ProgressDialog dlgProgress = null;

	final Handler hndLogin = new Handler() {
		public void handleMessage(Message msg) {
			String result = msg.getData().getString("result");
			if ("ok".equals(result)) {
				dlgProgress.dismiss();
				setResult(RESULT_OK, (new Intent()));
				finish();
				return;
			}
			if ("ko".equals(result)) {
				dlgProgress.dismiss();
				showErrorDialog(msg.getData().getString("error"));
				return;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		btnOk = (Button) findViewById(R.id.reg_btnOk);
		txtUsername = (EditText) findViewById(R.id.reg_txtUsername);
		txtPassword = (EditText) findViewById(R.id.reg_txtPasswd);
		btnOk.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// validate;
				dlgProgress = ProgressDialog.show(RegisterActivity.this, "",
						"Logging in. Please wait...", true);
				droiding.setUserAccount(txtUsername.getText().toString(),
						txtPassword.getText().toString(), hndLogin);
			}
		});
		droiding = Droiding.getInstance(this);
	}

	private void showErrorDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false).setPositiveButton("Retry",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						dlgProgress = ProgressDialog.show(RegisterActivity.this, "",
								"Logging in. Please wait...", true);
						droiding.setUserAccount(txtUsername.getText().toString(),
								txtPassword.getText().toString(), hndLogin);

					}
				}).setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

	}
}
